import tim from "../../tim";
const imUser = {
  state: {
    currentUserProfile: {},
    isLogin: false,
    isSDKReady: false // TIM SDK 是否 ready
  },
  mutations: {
    updateUserInfo(state, options) {
      var gender =
        options.sex == 1 ?
          "Gender_Type_Male" :
          options.sex == 2 ?
            "Gender_Type_Female" :
            "Gender_Type_Unknown";
      var avatar = options.avatar;
      var nick = options.nickname;
      tim
        .updateMyProfile({
          gender,
          avatar,
          nick
        })
        .then(() => {
          console.log(1);
        })
        .catch(imError => {
          //注释掉报错
          // window.$message.error(imError.message);
        });
    },
    updateCurrentUserProfile(state, userProfile) {
      state.currentUserProfile = userProfile;
    },
    toggleIsLogin(state, isLogin) {
      state.isLogin = typeof isLogin === "undefined" ? !state.isLogin : isLogin;
    },
    toggleIsSDKReady(state, isSDKReady) {
      state.isSDKReady = isSDKReady;
      // typeof isSDKReady === "undefined" ? !state.isSDKReady : isSDKReady;
    },
    reset(state) {
      Object.assign(state, {
        currentUserProfile: {},
        isLogin: false,
        isSDKReady: false // TIM SDK 是否 ready
      });
    }
  },
  actions: {
    login(context, info) {
      console.log(info);
      tim
        .login({
          userID: info.userID,
          userSig: info.userSig
        })
        .then(() => {
          context.commit("toggleIsLogin", true);
          context.commit("startComputeCurrent");
        })
        .catch(imError => {
          if (imError.code === 2000) {
            //注释掉报错
            // window.$message.error(
            //   imError.message + ", 请检查是否正确填写了 SDKAPPID"
            // );
          } else {
            //注释掉报错
            // window.$message.error(imError.message);
          }
        });
    },
    logout(context) {
      // 若有当前会话，在退出登录时已读上报
      if (context.rootState.conversation.currentConversation.conversationID) {
        tim.setMessageRead({
          conversationID: context.rootState.conversation.currentConversation.conversationID
        });
      }
      tim.logout().then(() => {
        context.commit("toggleIsLogin");
        context.commit("stopComputeCurrent");
        context.commit("reset");
      });
    }
  }
};

export default imUser;